Skip to main content

71. Simplify Path

Question

Given a string path, which is an absolute path (starting with a slash '/') to a file or directory in a Unix-style file system, convert it to the simplified canonical path.

In a Unix-style file system, a period '.' refers to the current directory, a double period '..' refers to the directory up a level, and any multiple consecutive slashes (i.e. '//') are treated as a single slash '/'. For this problem, any other format of periods such as '...' are treated as file/directory names.

The canonical path should have the following format:

The path starts with a single slash '/'. Any two directories are separated by a single slash '/'. The path does not end with a trailing '/'. The path only contains the directories on the path from the root directory to the target file or directory (i.e., no period '.' or double period '..') Return the simplified canonical path.

Example 1:

Input: path = "/home/"
Output: "/home"
Explanation: Note that there is no trailing slash after the last directory name.

Example 2:

Input: path = "/../"
Output: "/"
Explanation: Going one level up from the root directory is a no-op, as the root level is the highest level you can go.

Example 3:

Input: path = "/home//foo/"
Output: "/home/foo"
Explanation: In the canonical path, multiple consecutive slashes are replaced by a single one.

Constraints:

  • 1 <= path.length <= 3000
  • path consists of English letters, digits, period '.', slash '/' or '_'.
  • path is a valid absolute Unix path.

Approach

  1. Iterate through the path and look for directory names, i.e. those that are not '/' and append into a string
  2. Once we found a '/', the string we appended just now will be one of the file directories name. If that's the case, push it onto the stack.
  3. Else, if we encounter '.', we can ignore and proceed. If we encounter '..', we need to exit one level, which means we should pop off the top of the stack.
  4. Because there isn't a '/' at the end of path, we need to check for one last time for the deepest level of file directory.
  5. Append the final string by popping the stack, then iterate through the vector from the back to front (We need LILO here) and join each of the file directories with '/'.

Solution

class Solution {
public:
string simplifyPath(string path) {
stack<string> pathS;
string curr;

for(int i = 0; i < path.size(); i++){
if(path[i] != '/'){
curr += path[i];
}else{
if(curr.empty()) continue;
if(curr == "."){
curr = "";
continue;
}
if(curr == ".."){
if(!pathS.empty()) pathS.pop();
curr = "";
continue;
}
pathS.push(curr);
curr = "";
}
}

if(!curr.empty()){
if(curr == ".."){
if(!pathS.empty()) pathS.pop();
curr = "";
} else if (curr == "."){
curr = "";
}else{
pathS.push(curr);
curr = "";
}
}

vector<string> out;
string resp;
if(pathS.empty()) return "/";

while(!pathS.empty()){
out.push_back(pathS.top());
pathS.pop();
}

for(int i = out.size() - 1; i >= 0; i--){
resp += "/" + out[i];
}

return resp;
}
};